package dbgroup02.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import dbgroup02.bean.FlightTicket;
import dbgroup02.bean.Passenger;
import dbgroup02.bean.PassengerSelection;
import dbgroup02.bean.Ticket;
import dbgroup02.dao.FlightTicketDao;
import dbgroup02.dao.PassengerDao;
import dbgroup02.dao.TicketDao;

public class PassengerSelectionController extends SimpleFormController {
	
	private PassengerDao passengerDao;
	private TicketDao ticketDao;
	private FlightTicketDao flightTicketDao;
	
	public void setFlightTicketDao(FlightTicketDao flightTicketDao) {
		this.flightTicketDao = flightTicketDao;
	}
	
	public void setPassengerDao(PassengerDao passengerDao) {
		this.passengerDao = passengerDao;
	}
	public void setTicketDao(TicketDao ticketDao) {
		this.ticketDao = ticketDao;
	}
	
	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	protected ModelAndView onSubmit(HttpServletRequest request,	HttpServletResponse response, Object command, BindException errors)	throws Exception {
		
		PassengerSelection passengerSelection = (PassengerSelection) command;
		
		Ticket ticket = ticketDao.getTicket(Integer.parseInt(passengerSelection.getIdTicket()));
		if (ticket == null) { 
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("command", command);
			model.put("errorMessage", "Ticket not found in database");
			model.put("error", true);
			return new ModelAndView(getFormView(), model);
		}
		
		Passenger passenger = passengerDao.getPassenger(ticket.getIdPassenger());
		if (!passengerSelection.getLastName().equals(passenger.getLastName())) {
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("command", command);
			model.put("errorMessage", "There is no such passenger associated with this Ticket ID");
			model.put("error", true);
			return new ModelAndView(getFormView(), model);
		}
		
		List<FlightTicket> flightTickets = flightTicketDao.getFlightTickets(ticket.getIdTicket());
		if (flightTickets.get(0).getIdBoardingPass() > 0) {
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("command", command);
			model.put("errorMessage", "This passenger is already checked-in!");
			model.put("error", true);
			return new ModelAndView(getFormView(), model);
		}
		
		return new ModelAndView("redirect:seatselection.app?idTicket=" + ticket.getIdTicket());
	}

}
